package com.breeze.nfcdemo;

import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private NfcAdapter mNfcAdapter;
    private TextView mNFCMsgTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNFCMsgTV = findViewById(R.id.textView);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            mNFCMsgTV.setText("NFC is not available on this device.");
        } else {
            // 注册回调来设置 NDEF 消息,这样做可以使Activity处于前台时，NFC 数据推送处于激活状态。
            mNfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
                // 当前界面处于前台时，设备靠近后会触发传输界面，点击后，回调该方法获取ndef消息传输至两一台设备
                @Override
                public NdefMessage createNdefMessage(NfcEvent event) {
                    String text = String.format("Sending a message from nfcDemo at %s",
                            DateFormat.getTimeFormat(MainActivity.this).format(new Date()));
                    NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                            "text/plain", text.getBytes())
                            /**
                             * The Android Application Record (AAR) is commented out. When a device
                             * receives a push with an AAR in it, the application specified in the AAR
                             * is guaranteed to run. The AAR overrides the tag dispatch system.
                             * You can add it back in to guarantee that this
                             * activity starts when receiving a beamed message. For now, this code
                             * uses the tag dispatch system.
                             */
                            //,NdefRecord.createApplicationRecord("com.examples.nfcbeam")
                    );
                    return msg;
                }
            }, this);

            // 注册回调来监听消息发送成功
            mNfcAdapter.setOnNdefPushCompleteCallback(new NfcAdapter.OnNdefPushCompleteCallback() {
                @Override
                public void onNdefPushComplete(NfcEvent event) {
                    Toast.makeText(MainActivity.this, "Message Sent!", Toast.LENGTH_SHORT).show();
                }
            }, this);
        }
    }

    /**
     * 接收到消息后，会继续启动该Activity，onNewIntent回调
     *
     * @param intent
     */
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 在这之后会调用 onResume 来处理这个Intent
        setIntent(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 检查是否是一个Beam启动了这个Activity
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }

    /**
     * 处理收到的返回结果
     *
     * @param intent
     */
    void processIntent(Intent intent) {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        //  Beam 期间只发送了一条消息
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // 记录 0 包含了 MIME 类型
        mNFCMsgTV.setText(new String(msg.getRecords()[0].getPayload()));
    }
}
